package xyz.zhzby.cyzx.security.security;

import io.swagger.annotations.ApiModel;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import xyz.zhzby.cyzx.servicebase.domain.RestResponse;
import xyz.zhzby.cyzx.servicebase.utils.ResponseUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zby
 * @date 2021/12/07
 */
@ApiModel("退出处理器")
public class TokenLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;

    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String token = request.getHeader("token");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring("Bearer ".length());
            //清空当前用户缓存中的权限数据
            String userName = tokenManager.getUserFromToken(token);
            tokenManager.removeToken(redisTemplate, userName);
        }
        ResponseUtil.out(response, RestResponse.success("登出成功"));
    }

}
